import { createRouter, createWebHistory, useRouter } from 'vue-router'
import { requiredRoutes } from '@/router/routes'
import { useRouterStore, useAuthStore } from '@/store'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: requiredRoutes,
})

router.beforeEach(async (to, from, next) => {
  console.log('进入导航守卫')
  const routerStore = useRouterStore()
  const authStore = useAuthStore()
  const { isRouteLoad } = storeToRefs(routerStore)
  const { isAuthenticated } = storeToRefs(authStore)

  if (to.meta?.requiresAuth && !isAuthenticated.value) {
    next('/login')
    return
  }

  if (!isRouteLoad.value) {
    try {
      await routerStore.filterRoutes()
    } catch (error) {
      next('/login')
      ElMessage.error('路由加载失败')
      return
    }
  }

  next()
})

export default router
